package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品
     *
     * @param dto
     */
    @Override
    @Transactional  // 开启事务：涉及多表增删改查都需要开启事务处理
    public void add(DishDTO dto) {
        /* 1、构造菜品基础数据、将其存入dish表中 */
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish); // 拷贝属性
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());

        /* 保存Dish数据 */
        dishMapper.add(dish);

        /* 2、构造菜品口味到表数据、将其存入dish_flavor表中 */
        List<DishFlavor> dishFlavorList = dto.getFlavors();
        dishFlavorList.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.addBatch(dishFlavorList);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        /* 设置分页参数 */
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        /* 调用mapper方法 */
        Page<DishVO> page = dishMapper.page(dto);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        /* 1、在删除菜品之前需要判断 菜品是否起售，起售的菜品不允许删除 */
        ids.forEach(item -> {
            Dish dish = dishMapper.selectById(item);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        /* 2、判断菜品是否被套餐关联，关联的菜品不允许被删除 */
        Integer count = setmealDishMapper.countByDishId(ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        /* 3、开始删除：删除菜品基本信息 dish 表 */
        dishMapper.deleteByIds(ids);
        /* 4、删除菜品口味信息 dish_flavor 表 */
        dishFlavorMapper.deleteByIds(ids);
    }

    /**
     * 根据id回显菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();

        /* 1、根据菜品id查询菜品基本信息 */
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish, dishVO);

        /* 2、根据菜品id查询口味信息 */
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dto
     */
    @Override
    @Transactional
    public void update(DishDTO dto) {
        /* 修改 菜品信息 dish 表 */
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.update(dish);

        /* 先全部删除 在进行新增 */
        dishFlavorMapper.deleteDishById(dto.getId());

        List<DishFlavor> flavors = dto.getFlavors();

        if (flavors != null && flavors.size() > 0) {
            /* 关联菜品id */
            flavors.forEach(item -> {
                item.setDishId(dish.getId());
            });
            dishFlavorMapper.addBatch(flavors);
        }
    }

    /**
     * 修改菜品停售起售状态
     * @param status
     */
    @Override
    public void status(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        dishMapper.update(dish);
    }

    /**
     * 用户端-根据id查询菜品信息
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOS = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOS.add(dishVO);
        }
        return dishVOS;
    }


}
